package org.example.netty.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.config.NettyClientConfig;
import org.example.netty.handler.channel.CustomProtocolDecoder;
import org.example.netty.handler.channel.CustomProtocolEncoder;
import org.example.netty.handler.channel.HeartbeatHandler;
import org.example.netty.handler.message.MessageHandlerFactory;
import org.example.netty.handler.channel.ClientBusinessHandler;
import org.example.netty.mgt.ClientConnectionManager;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NettyClient extends AbstractNettyEndpoint{
    private Thread thread;
    private NettyClientConfig config;

    public NettyClient(NettyClientConfig config,ClientConnectionManager connectionManager, MessageHandlerFactory messageHandlerFactory) {
        super(connectionManager, messageHandlerFactory,new ThreadPoolExecutor(20,200,360, TimeUnit.SECONDS
                ,new ArrayBlockingQueue<>(100),new EndpointThreadFactory("netty-client-")));
        this.config=config;
    }

    @Override
    public void start() {
        thread=new Thread(()->{

            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast("cdecoder",new CustomProtocolDecoder())//向pipeline 加入解码器
                                    .addLast("cencoder",new CustomProtocolEncoder())//向pipeline 加入编码器
                                    .addLast("heartbeat",new HeartbeatHandler(connectionManager))//向pipeline 加入心跳handler
                                    .addLast("business",new ClientBusinessHandler(connectionManager,businessThreadPool,messageHandlerFactory))//业务处理器
                            ;
                        }
                    });
            try {
                ChannelFuture channelFuture = bootstrap.connect(config.getAddress(), config.getPort()).sync();
                /*Channel channel = channelFuture.channel();
                connectionManager.putChannel(channel);*/
                log.info("=====================  netty Client端启动成功  ===========================");
                channelFuture.channel().closeFuture().sync();
            }catch (InterruptedException e){
                log.error(">>>>>>>> netty-client 停止服务 ");
            }
        });
        thread.setName("netty-client-thread");
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public void shutdown() {
        businessThreadPool.shutdown();
        if (thread!=null && thread.isAlive()) {
            thread.interrupt();
        }
    }

    public void reconnect() {

    }
}
